<template>
    <div>
        <a-upload
            name="file"
            list-type="picture-card"
            class="image-uploader"
            :show-upload-list="false"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :before-upload="beforeUpload"
            @change="handleChange"
            >
            <img v-if="imageUrl" :src="`/upload/${imageUrl}`" alt="Image" />
            <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                    上传文件
                </div>
            </div>
        </a-upload>
    </div>
</template>

<script>

    export default {
        props:{
            value:String,
            path:String,  //通过path传入远程图片处理接口
        },        
        model:{
            prop:'value',
            event:'change'
        },
        data(){
            return{
                loading: false,
                imageUrl: '',
            }
        },

        watch:{
            value:{
                handler: function(val){
                    this.loading = false;
                    this.imageUrl = '';
                    if (val) {
                        this.imageUrl = val;
                    }
                }
            }
        },
        created(){
            this.uploadUrl = '/api/adminGoodsOperation/upFile';
            this.uploadHeaders = {
                // 通过这里传headers信息
            }
        },
        methods:{
            handleChange(info) {
                console.log(info)
                if (info.file.status === 'uploading') {
                    this.loading = true;
                    return;
                }
                if (info.file.status === 'done') {
                    // 因为是内部应用，所以这里没有使用base64编码本地图片，而是直接加载远程图片，暴力而直接
                    this.imageUrl = info.file.response;
                    this.loading = false;
                    this.$emit('change', this.imageUrl);
                }
            },
            beforeUpload(file) {
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                if (!isJpgOrPng) {
                    this.$message.error('只能上传png或jpg格式的图片!');
                }
                const isLt2M = file.size / 1024 / 1024 < 10;
                if (!isLt2M) {
                    this.$message.error('图片尺寸不能超过 10MB!');
                }
                return isJpgOrPng && isLt2M;
            },
        }
        

    }
</script>

<style scoped>
    .image-uploader > .ant-upload {
        width: 128px;
        height: 128px;
    }
    /*css水平有限，简单限制一下加载的图片尺寸*/
    .image-uploader > .ant-upload img{
        max-width: 100%;
        max-height: 100%;
    }
    .ant-upload-select-picture-card i {
        font-size: 32px;
        color: #999;
    }

    .ant-upload-select-picture-card .ant-upload-text {
        margin-top: 8px;
        color: #666;
    }
</style>